<template>
  <div>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          style="background: #2f54eb"
          @click="handleAdd"
          size="small"
          v-hasPermi="['report:set:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="setList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" v-if="false" />
      <el-table-column label="数据集名称" align="left" prop="reportSetName" />
      <el-table-column label="所属数据源" align="left" prop="reportDatabaseId" />
      <el-table-column
        label="数据集描述"
        align="left"
        prop="reportSetRemark"
      />
      <el-table-column
        label="操作"
        align="center"
        width="150"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['report:set:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['report:set:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据集对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
<!--        <el-form-item label="所属数据源" prop="reportDatabaseId">
          <el-input v-model="form.reportDatabaseId" placeholder="请输入所属数据源" />
        </el-form-item>-->
        <el-form-item label="数据集名称" prop="reportSetName">
          <el-input
            v-model="form.reportSetName"
            placeholder="请输入数据集名称"
          />
        </el-form-item>
        <el-form-item label="数据集描述" prop="reportSetRemark">
          <el-input
            v-model="form.reportSetRemark"
            type="textarea"
            placeholder="请输入数据集描述"
          />
        </el-form-item>
        <el-form-item label="执行SQL" prop="reportSetSql">
          <codeEdit
            :modelValue="form.reportSetSql"
            @editSetvalue="editSetvalue"
            mode="sql"
          ></codeEdit>
        </el-form-item>
        <el-alert
          title="添加查询参数时请使用':参数名称' 如: select * from emp where dept_id = :deptId"
          type="success"
          style="
            margin-left: 120px;
            width: calc(100% - 120px);
            margin-bottom: 20px;
          "
        >
        </el-alert>
        <el-form-item label="查询参数" prop="reportSetParams">
          <div class="addbtn" style="margin-bottom: 10px">
            <el-button type="primary" @click="add" size="mini">新 增</el-button>
            <el-button
              type="danger"
              @click="deleteData"
              :disabled="!chooseList.length"
              size="mini"
              >删 除</el-button
            >
          </div>
          <el-table
            ref="multipleTable"
            :data="form.reportSetParams"
            tooltip-effect="dark"
            style="width: 100%"
            border
            @selection-change="handleSelectionChangeChild"
          >
            <el-table-column type="selection" width="55" align="center">
            </el-table-column>
            <el-table-column
              label="参数名称"
              width="200"
              align="center"
              prop="name"
            >
              <template slot-scope="scope"
                ><el-input
                  v-model="scope.row.name"
                  placeholder="请输入参数名称"
              /></template>
            </el-table-column>
            <el-table-column
              prop="type"
              label="参数类型"
              width="200"
              align="center"
            >
              <template slot-scope="scope"
                ><el-select v-model="scope.row.type" placeholder="请选择">
                  <el-option
                    v-for="item in dict.type.pt_app_report_cxparam"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option> </el-select
              ></template>
            </el-table-column>
            <el-table-column
              prop="defaultValue"
              label="默认值"
              show-overflow-tooltip
              align="center"
            >
              <template slot-scope="scope"
                ><el-input
                  v-model="scope.row.defaultValue"
                  placeholder="请输入默认值"
              /></template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-alert title="系统默认参数：deptId、userId、userName"
          type="success" style="margin-left: 120px;width: calc(100% - 120px);" >
        </el-alert>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          :loading="buttonLoading"
          type="primary"
          @click="submitForm"
          size="small"
          >确 定</el-button
        >
        <el-button @click="cancel" size="small">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSet,
  getSet,
  delSet,
  addSet,
  updateSet,
} from "@/api/app/report";
import codeEdit from "@/components/codeEdit";
import { uuid } from "vue-uuid";
export default {
  name: "dataSet",
  components: {
    codeEdit,
  },
  dicts: ["pt_app_report_cxparam"],
    props: {
   appId:{
      type:String,
      default:''
    }
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据集表格数据
      setList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      chooseList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        reportDatabaseId: '1706184258461986818',
        reportSetName: undefined,
        reportSetSql: undefined,
        reportSetParams: [],
        reportSetRemark: undefined,
        org: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [{ required: true, message: "主键不能为空", trigger: "blur" }],
        reportDatabaseId: [
          { required: true, message: "所属数据源不能为空", trigger: "blur" },
        ],
        reportSetName: [
          { required: true, message: "数据集名称不能为空", trigger: "blur" },
        ],
        reportSetSql: [
          { required: true, message: "执行SQL不能为空", trigger: "blur" },
        ],
        reportSetRemark: [
          { required: true, message: "数据集描述不能为空", trigger: "blur" },
        ],
        org: [{ required: true, message: "不能为空", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleSelectionChangeChild(arr) {
      this.chooseList = arr;
    },
    add() {
      this.form.reportSetParams = [
        ...this.form.reportSetParams,
        { uuid: uuid.v1(), name: "id", type: "String", defaultValue: "" },
      ];
    },
    deleteData() {
      this.$confirm("此操作将删除选中数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.form.reportSetParams = this.form.reportSetParams.filter(
            (item) =>
              !this.chooseList.some(
                (ele) =>
                  ele.uuid === item.uuid || (ele.id && ele.id === item.id)
              )
          );
          this.chooseList = [];
        })
        .catch(() => {});
    },
    editSetvalue(value) {
      this.form = { ...this.form, reportSetSql: value };
    },
    /** 查询数据集列表 */
    getList() {
      this.loading = true;
      listSet(this.queryParams).then((response) => {
        this.setList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        reportDatabaseId: '1706184258461986818',
        reportSetName: undefined,
        reportSetSql: undefined,
        reportSetParams: [],
        reportSetRemark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        org: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据集";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids;
      getSet(id).then((response) => {
        this.loading = false;
        this.form = {...response.data,reportSetParams:JSON.parse(response.data?.reportSetParams)};
        this.open = true;
        this.title = "修改数据集";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateSet({...this.form,reportSetParams:JSON.stringify(this.form?.reportSetParams),appId:this.appId})
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addSet({...this.form,reportSetParams:JSON.stringify(this.form?.reportSetParams),appId:this.appId})
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除数据集？')
        .then(() => {
          this.loading = true;
          return delSet(ids);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    }
  }
};
</script>
